/**
 * 搜索组件
 * Created by yangbajing(yangbajing@gmail.com) on -11-15.
 */
import React, {Component, PropTypes} from "react";
import {Form, Row, Radio, Col, Button, Icon} from "antd";
import lodashKeys from "lodash/keys";
import lodashChunk from "lodash/chunk";
import lodashIsEqual from 'lodash/isEqual';
import {createFormItem} from "../commons/form";
const ButtonGroup = Button.Group;

const SPLIT_SIZE = 4;

/**
 * 找到第一个有值的control索引
 * @param controls
 */
function findFirstValueIndex(controls) {
    for (let i = 0; i < controls.length; i++) {
        const control = controls[i];
        if (!control.options || !control.options.initialValue) {
            continue;
        }

        if ((control.type == 'rangeDatePicker' || control.type == 'checkbox')
            && control.options.initialValue.length > 0) {
            return i;
        } else if (control.props &&
            control.props.multiprowColle &&
            control.options.initialValue.length > 0) {
            return i;
        } else {
            return i;
        }
    }
    return -1;
}

function isExpand(controls) {
    return findFirstValueIndex(controls) > (SPLIT_SIZE - 1);
}

class SearchComponent extends Component {
    static propTypes = {
        controls: PropTypes.arrayOf(PropTypes.object).isRequired,
        onSearch: PropTypes.func.isRequired,
        onDownload: PropTypes.func,
        onClean: PropTypes.func
    };

    static defaultProps = {
        rowCol: SPLIT_SIZE
    };

    constructor(props) {
        super(props);
        this.state = {
            expand: isExpand(props.controls)
        };
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(this.props.controls, nextProps.controls)) {
            if (isExpand(nextProps.controls)) {
                this.setState({expand: true});
            }
        }
    }

    toggle = () => {
        const {expand} = this.state;
        this.setState({expand: !expand});
    };

    handleClear = () => {
        const value = this.props.form.getFieldsValue();
        let values = {};
        this.props.controls.forEach(control => {
            switch (control.type) {
                case 'rangeDatePicker':
                case 'checkbox':
                    values[control.name] = [];
                    break;
                case 'select':
                    if (control.props && control.props.multiple)
                        values[control.name] = [];
                    else
                        values[control.name] = null;
                    break;
                default:
                    values[control.name] = null;
            }
        });
        this.props.form.setFieldsValue(values);
        if (this.props.onClean) {
            this.props.onClean(value);
        }
    };

    handleSearch = () => {
        const {form} = this.props;
        const value = form.getFieldsValue();
        let realValue = {};
        for (const key of lodashKeys(value)) {
            if (value[key])
                realValue[key] = value[key];
        }
        this.props.onSearch(realValue);
    };

    handleDownload = () => {
        if (this.props.onDownload) {
            const {form} = this.props;
            const value = form.getFieldsValue();
            let realValue = {};
            for (const key of lodashKeys(value)) {
                if (value[key])
                    realValue[key] = value[key];
            }
            this.props.onDownload(realValue);
        }
    };

    render() {
        const {controls, form} = this.props;

        let controlGroups = lodashChunk(controls, this.props.rowCol);
        if (!this.state.expand) {
            controlGroups = controlGroups.slice(0, 1);
        }

        const colSpan = 24 / this.props.rowCol;

        const formItems = controlGroups
            .map((list, rowIdx) => {
                const items = list.map((config, idx) =>
                    <Col span={colSpan} key={idx}>{createFormItem(form.getFieldDecorator, config, idx)}</Col>);
                return <Row key={rowIdx} gutter={24}>{items}</Row>
            });

        let moreElement = <noscript/>;
        if (controls.length > this.props.rowCol) {
            moreElement = (
                <a style={{marginLeft: '1rem', color: '#444'}} onClick={this.toggle}>
                    <small>更多搜索</small>
                    &nbsp;
                    <Icon type={this.state.expand ? 'up' : 'down'}/>
                </a>
            );
        }

        const downloadElement = this.props.onDownload
            ? <Button type="ghost" icon="download" onClick={this.handleDownload}>下载</Button>
            : <noscript/>;

        return (
            <Form horizontal>
                {formItems}
                <Row>
                    <Col span={24} style={{textAlign: 'right'}}>
                        {downloadElement}
                        <ButtonGroup>
                            <Button type="ghost"
                                    onClick={this.handleClear}>清空</Button>
                            <Button type="primary" htmlType="submit"
                                    onClick={this.handleSearch}>搜索</Button>
                        </ButtonGroup>
                        {moreElement}
                    </Col>
                </Row>
            </Form>
        )
    }
}

export default Form.create({})(SearchComponent);
